package com.epoch.fy.user.service;

import java.util.List;

import com.epoch.fy.user.dao.LevelSet;
import com.epoch.fy.user.dao.Session;
import com.epoch.fy.user.dao.User;
import com.epoch.fy.user.dao.UserSign;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
/**
 * 
* <p>Title: UserService.java</p>  
* <p>Description: </p>  
* @author 张清磊
* @QQ 544188838
* @date 2018年9月24日
 */
public class UserService {
	
	public static final UserService me = new UserService();
	
	// 存放登录用户的 cacheName
	public static final String loginAccountCacheName = "loginAccount";
	
	public static final String sessionIdName = "epochFlyId";
	
	public static final String userSignCacheName = "userSign";
	
	public static final String USER_AVASTAR = "//q.qlogo.cn/qqapp/101235792/F9D188DE2C24AE9590785EA4EC5ADC24/100";
	
	public Ret login(String account,String password) {
		User user = User.dao.findFirst("select * from fly_user where email =? limit 1", account);
		if (user == null) {
			return Ret.fail("msg", "用户名或密码不正确");
		}
		if(user.isLocked().isFail()) {
			return user.isLocked();
		}
		String salt = user.getStr(User.SALT);
		String hashedPass = HashKit.sha256(salt + password);
		// 未通过密码验证
		if (!user.getStr(User.PASSWORD).equals(hashedPass)) {
			return Ret.fail("msg", "用户名或密码不正确");
		}
		user.removeSensitiveInfo();
		long liveSeconds =  120 * 60;
		long expireAt = System.currentTimeMillis() + (liveSeconds * 1000);
		Session session = new Session();
		String sessionId = StrKit.getRandomUUID();
		session.set(Session.ID, sessionId);
		session.set(Session.USER_ID, user.getInt(User.ID));
		session.set(Session.EXPIRE_DATE, expireAt);
		if (!session.save()) {
			return Ret.fail("msg", "保存 session 到数据库失败，请联系管理员");
		}
		CacheKit.put(loginAccountCacheName, sessionId, user);
		return Ret.ok(sessionIdName, sessionId)
				.set(loginAccountCacheName, user);
	}
	
	public User getLoginAccountWithSessionId(String sessionId) {
		return CacheKit.get(loginAccountCacheName, sessionId);
	}
	
	public User loginWithSessionId(String sessionId, String loginIp) {
		Session session = Session.dao.findById(sessionId);
		if (session == null) {      // session 不存在
			return null;
		}
		if (session.isExpired()) {  // session 已过期
			session.delete();		// 被动式删除过期数据，此外还需要定时线程来主动清除过期数据
			return null;
		}

		User loginAccount = User.dao.findById(session.getStr(Session.USER_ID));
		// 找到 loginAccount 并且 是正常状态 才允许登录
		if (loginAccount != null && loginAccount.isLocked().isOk()) {
			loginAccount.removeSensitiveInfo();                                 // 移除 password 与 salt 属性值
			loginAccount.put("sessionId", sessionId);                          // 保存一份 sessionId 到 loginAccount 备用
			CacheKit.put(loginAccountCacheName, sessionId, loginAccount);
			return loginAccount;
		}
		return null;
	}
	
	/**
	 * 退出登录
	 */
	public void logout(String sessionId) {
		if (sessionId != null) {
			CacheKit.remove(loginAccountCacheName, sessionId);
			Session.dao.deleteById(sessionId);
		}
	}
	
	public UserSign getUserSign(Integer userId) {
		Kv param = Kv.create();
		param.put("user_id", userId);
		SqlPara sqlPara = Db.getSqlPara("fly.findUserSignByUserId", param);
		UserSign userSign = UserSign.dao.findFirst(sqlPara);
		return userSign;
	}
	
	public int getGold(int signCount) {
		if(signCount<30) {
			return 1;
		}
		if(signCount>30 && signCount < 365) {
			return 2;
		}
		if(signCount>=365) {
			return 3;
		}
		return 1;
	}
	
	public LevelSet getLevelSetId(int exp) {
		Kv param = Kv.create();
		SqlPara sqlPara = Db.getSqlPara("fly.findLevelSetAll", param);
		List<LevelSet> list = LevelSet.dao.find(sqlPara);
		LevelSet level_result = null;
		for (int i = 0; i < list.size(); i++) {
			LevelSet level = list.get(i);
			if(exp<=level.getInt(LevelSet.EXP)) {
				level_result = level;
				break;
			}
		}
		if(null == level_result) {
			return list.get(list.size()-1);
		}
		return level_result;
	}
	
	public LevelSet getLevelFirst() {
		Kv param = Kv.create();
		SqlPara sqlPara = Db.getSqlPara("fly.findLevelSetAll", param);
		List<LevelSet> list = LevelSet.dao.find(sqlPara);
		return list.get(0);
	}
	
	public boolean vlidateRegisn(String email,String username) {
		Kv param = Kv.create();
		param.put("email", email);
		param.put("nickname", username);
		SqlPara sqlPara = Db.getSqlPara("fly.findVlidateRegisn", param);
		User user = User.dao.findFirst(sqlPara);
		if(null != user) {
			return true;
		}
		return false;
	}
}
